<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="60%"
    title="多规格设置"
    :style="{ top: '20px' }"
  >
    <div
      v-if="visible"
      style="max-height: 600px; overflow-y: auto"
      v-permission="['base-data:product:spec:query']"
      v-loading="loading"
    >
      <a-collapse v-model:activeKey="propertyIds">
        <a-collapse-panel
          v-for="item in propertyData"
          :key="item.id"
          :header="item.name"
          :bordered="false"
        >
          <vxe-grid
            ref="grid"
            resizable
            show-overflow
            highlight-hover-row
            keep-source
            row-id="id"
            :height="tableData[item.id].length * 50"
            :data="tableData[item.id]"
            :columns="tableColumn[item.id]"
            :toolbar-config="toolbarConfig"
          >
            <!-- 工具栏 -->
            <template #toolbar_buttons> </template>
            <template #property_default="{ row }">
              {{
                propertyData
                  .find((p) => p.id === row.propertyId)
                  .items.find((i) => i.id === row.itemId).name
              }}
            </template>
            <template #price_default="{ column, row }">
              <a-input-number
                style="width: 100%"
                v-model:value="row[column.field]"
                min="0"
                placement="2"
                @change="
                  (val) => {
                    if (!val) {
                      row[column.field] = 0.0;
                    }
                  }
                "
              />
            </template>
            <template #available_default="{ column, row }">
              <a-switch v-model:checked="row[column.field]" />
            </template>
            <!-- 操作 列自定义内容 -->
            <template #action_default="{ row }">
              <a-space>
                <div>
                  <a-button type="link" @click="costSet(row)"> 成本设置 </a-button>
                  <a-badge
                    :count="row?.costDetailData.length"
                    :number-style="{ backgroundColor: '#52c41a' }"
                  />
                </div>
              </a-space>
            </template>
          </vxe-grid>
        </a-collapse-panel>
      </a-collapse>
    </div>
    <template #footer>
      <div class="form-modal-footer" v-permission="['base-data:product:spec:add']">
        <a-space>
          <a-button type="primary" :loading="loading" html-type="submit" @click="submit">
            保存
          </a-button>
          <a-button :loading="loading" @click="closeDialog">取消</a-button>
        </a-space>
      </div>
    </template>
  </a-modal>

  <spec-cost-edit
    ref="specCostEditRef"
    :product-id="productId"
    :property-id="propertyId"
    :item-id="itemId"
    :cost-detail-data="costDetailData"
  />
</template>

<script setup>
  // 弹窗是否可见
  import { getCurrentInstance, reactive, ref } from 'vue';
  import * as api from '@/api/base-data/product/spec';
  import * as productApi from '@/api/base-data/product/info';
  import * as propertyApi from '@/api/base-data/product/property';
  import SpecCostEdit from '@/views/base-data/product/spec/specCostEdit.vue';

  // this对象
  const instance = getCurrentInstance();

  const emit = defineEmits(['confirm', 'close']);

  const visible = ref(false);

  // 加载中
  const loading = ref(false);

  const props = defineProps({
    productId: {
      type: String,
      required: true,
    },
  });

  const propertyId = ref('');

  const itemId = ref('');

  const grid = ref();

  const specCostEditRef = ref();

  //
  const tableData = ref({});

  // 表格列配置
  const tableColumn = ref({});

  const defaultColumns = ref([
    { field: 'purchasePrice', title: '采购价', minWidth: 120, slots: { default: 'price_default' } },
    { field: 'retailPrice', title: '零售价', minWidth: 120, slots: { default: 'price_default' } },
    { field: 'salePrice', title: '销售价', minWidth: 120, slots: { default: 'price_default' } },
    { field: 'available', title: '状态', width: 80, slots: { default: 'available_default' } },
    { title: '操作', width: 120, fixed: 'right', slots: { default: 'action_default' } },
  ]);

  // 工具栏配置
  const toolbarConfig = reactive({
    // 缩放
    zoom: false,
    // 自定义表头
    custom: false,
    // 右侧是否显示刷新按钮
    refresh: false,
    // 自定义左侧工具栏
    slots: {
      buttons: 'toolbar_buttons',
    },
  });

  const productData = ref({});

  const propertyData = ref({});

  const propertyIds = ref([]);

  const costDetailData = ref([]);

  const initData = () => {};

  const initTableColumn = () => {
    tableColumn.value = {};
    propertyData.value.forEach((property) => {
      tableColumn.value[property.id] = [];
      tableColumn.value[property.id].push({
        field: property.id,
        title: property.name,
        width: 120,
        slots: { default: 'property_default' },
      });
      tableColumn.value[property.id].push(...defaultColumns.value);
    });
  };

  const createActions = (row) => [
    {
      label: '成本设置',
      onClick: () => {
        propertyId.value = row.propertyId;
        itemId.value = row.itemId;
        costDetailData.value = row.costDetailData;
        specCostEditRef.value.openDialog();
      },
    },
  ];

  // 成本设置
  const costSet = (row) => {
    propertyId.value = row.propertyId;
    itemId.value = row.itemId;
    costDetailData.value = row.costDetailData;
    specCostEditRef.value.openDialog();
  };

  const initTableData = () => {
    tableData.value = {};
    propertyData.value.forEach((property) => {
      tableData.value[property.id] = [];
      property.items.forEach((item) => {
        tableData.value[property.id].push({
          propertyId: property.id,
          itemId: item.id,
          purchasePrice: 0.0,
          retailPrice: 0.0,
          salePrice: 0.0,
          available: false,
          costDetailData: [],
        });
      });
    });
  };

  // 查询数据
  const loadFormData = (productId) => {
    loading.value = true;
    productApi
      .get(productId)
      .then((data) => {
        productData.value = data;
        let categoryId = data.categoryId;
        propertyApi
          .getModelorByCategory(categoryId)
          .then((res) => {
            propertyData.value = res;
            propertyIds.value = [...propertyData.value.map((item) => item.id)];
            initTableColumn();
            initTableData();
            // 填充表格数据
            loading.value = true;
            api.query({ productId }).then((res) => {
              res?.forEach((item) => {
                tableData.value[item.propertyId].forEach((t) => {
                  if (t.itemId === item.itemId) {
                    t.purchasePrice = item.purchasePrice;
                    t.retailPrice = item.retailPrice;
                    t.salePrice = item.salePrice;
                    t.available = item.available;
                    t.costDetailData = item.costDetailData || [];
                  }
                });
              });
            });
          })
          .finally(() => {
            loading.value = false;
          });
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 打开弹窗
  const openDialog = (productId) => {
    visible.value = true;
    initData();
    loadFormData(productId);
  };

  // 数据提交
  const submit = () => {
    loading.value = true;
    const data = [];
    Object.keys(tableData.value).forEach((key) => {
      data.push(...tableData.value[key]);
    });
    api
      .save(props.productId, data)
      .then(() => {
        _This().$message.success('保存成功');
        emit('confirm');
        closeDialog();
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 关闭对话框
  const closeDialog = () => {
    visible.value = false;
    emit('close');
  };

  // 组件实例对象
  const _This = () => {
    return instance.appContext.config.globalProperties;
  };

  defineExpose({
    openDialog,
  });
</script>

<style scoped></style>
